import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:p_location/common/res/common_res.dart';
import 'package:p_location/common/widget/common_app_bar.dart';
import 'package:p_location/map/constant/map_http_url.dart';
import 'package:p_location/map/res/dept_tree_info.dart';
import 'package:p_location/map/res/dept_tree_res.dart';
import 'package:p_location/map/widget/dept_item_view.dart';
import 'package:p_location/net/dio_http_client.dart';
import 'package:p_location/net/net_listener.dart';

class DeptInfoTreePage extends StatefulWidget {
//  final ClickType mode;
  final bool isFromSearch;

  @override
  State<StatefulWidget> createState() {
    return _DeptInfoTreePageState();
  }

  const DeptInfoTreePage({
    Key key,
//    this.mode = ClickType.viewMode,
    this.isFromSearch = false,
  });
}

class _DeptInfoTreePageState extends State<DeptInfoTreePage>
    implements NetListener {
  bool isLoading = true;
  List<DeptTreeInfo> origins = [];
  List<DeptTreeInfo> lists = [];

  @override
  void initState() {
    super.initState();
    realRequest();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: _getCommonAppBar(),
      body: Container(
        color: Colors.white,
        child: Stack(
          children: <Widget>[_getContentView()],
        ),
      ),
    );
  }

  _getContentView() {
    if (isLoading) {
      return _getLoadingView();
    }
    return _listView();
  }

  _getLoadingView() {
    return Center(
      child: Image.asset('images/timg.gif'),
    );
  }

  _listView() {
    return ListView.separated(
        itemBuilder: (context, index) {
          return createListViewItem(index);
        },
        separatorBuilder: (context, index) {
          return Divider(
            color: Colors.grey,
            height: 0.4,
          );
        },
        itemCount: lists.length);
  }

  _getCommonAppBar() {
    return CommonAppBar(
      hiddenBack: false,
      title: Text(
        '组织机构',
        style: TextStyle(color: Colors.black),
      ),
      actions: [],
      onPress: () {
        Navigator.pop(context);
      },
    );
  }

  createListViewItem(index) {
    DeptTreeInfo deptObj = lists[index];
    return Padding(
      padding: EdgeInsets.only(left: (deptObj.level - 1) * 20.0),
      child: DeptItemView(deptObj, () {
        print(deptObj.children);
        print('选择了${deptObj.label}');
        Navigator.pop(context, deptObj);
      }, () {
        if (deptObj.children != null && deptObj.children.length > 0) {
          setState(() {
            recursiveConfigFlag(
                origins, deptObj.id, deptObj.isShow, !deptObj.isExpand);
            if (origins != null) {
              lists = [];
              recursiveDeptInfos(origins, 0);
            }
          });
        }
      }),
    );
  }

  realRequest() async {
    Map<String, dynamic> params = {};
    await DioHttpClient.requestGet(
        context, MapHttpUrl.DEPT_LIST_URL, params, this);
  }

  @override
  void onRequestSuccess(Response response) {
    setState(() {
      lists.clear();
      isLoading = false;
      if (response != null && response.data != null) {
        DeptTreeRes listRes = DeptTreeRes.fromJson(response.data);
        if (listRes != null && listRes.data != null) {
          origins = [listRes.data];

          if(origins!=null){
            origins.forEach((dept) {
              recursiveConfigFlag(
                  origins, dept.id, dept.isShow, !dept.isExpand);
              recursiveDeptInfos(origins, 0);
            });
          }

        }
      }
    });
  }

  recursiveCollapse(List<DeptTreeInfo> nodes) {
    if (nodes == null || nodes.length == 0) {
      return;
    }
    nodes.forEach((o) {
      o.isShow = false;
      o.isExpand = false;
      recursiveCollapse(o.children);
    });
  }

  recursiveConfigFlag(List<DeptTreeInfo> nodes, targetId, showFlag, expandFlag) {
    if (nodes == null) {
      return;
    }
    nodes.forEach((dept) {
      if (dept.id == targetId) {
        dept.isShow = showFlag;
        dept.isExpand = expandFlag;
        if (dept.children != null) {
          dept.children.forEach((o) {
//            if (o.className == 'el-icon-staff') {
//            if (dept.className == 'el-icon-folder') {
            o.isShow = expandFlag;
            dept.isExpand = expandFlag;

//            } else {
//              o.isShow = dept.isExpand;
//              o.isExpand = false;
//            }

//            o.isExpand = showFlag;
//            }
          });
          if (!expandFlag) {
            recursiveCollapse(dept.children);
          }
        }
      } else {
        if (dept.children != null && dept.children.length != 0) {
          recursiveConfigFlag(dept.children, targetId, showFlag, expandFlag);
        }
      }
    });
  }

  recursiveDeptInfos(List<DeptTreeInfo> depts, int initLevel) {
    if (depts == null) {
      return;
    }
    initLevel++;
    depts.forEach((dept) {
      dept.level = initLevel;
//      if (dept.className == 'el-icon-folder' ||
//          (dept.className == "el-icon-staff" && dept.isExpand)) {
//        lists.add(dept);
//      }
      if (dept.level == 1 || dept.isShow) {
        lists.add(dept);
      }
      if (dept.children != null && dept.children.length != 0) {
        recursiveDeptInfos(dept.children, initLevel);
      }
    });
  }

  @override
  void onRequestError(CommonRes errorRes) {}
}
